import { create } from 'zustand';
import { getItems as apiGetItems, createItem as apiCreateItem } from '../services/api';

export const useAppStore = create((set, get) => ({
  // --- STATE ---
  items: [],
  isLoading: false,
  error: null,
  selectedCategoryId: null,
  selectedToolId: null,

  // --- ACTIONS ---
  selectCategory: (categoryId) => set(() => ({ 
    selectedCategoryId: categoryId, 
    selectedToolId: null // Reset tool selection when category changes
  })),
  
  selectTool: (toolId) => set(() => ({ selectedToolId: toolId })),

  // Actions for items
  fetchItems: async () => {
    set({ isLoading: true, error: null });
    try {
      const response = await apiGetItems();
      set({ items: response.data, isLoading: false });
    } catch (error) {
      set({ error: error.message, isLoading: false });
    }
  },

  createItem: async (title) => {
    set({ isLoading: true, error: null });
    try {
      await apiCreateItem({ title });
      // After creating, refresh the list
      get().fetchItems();
    } catch (error) {
      set({ error: error.message, isLoading: false });
    }
  },
}));
